{% extends 'base/base.html' %}
{% load static %}
{% block css %}

<link href="/static/assets/css/font-awesome.min.css" rel="stylesheet"/>
<link href="/static/assets/css/jquery-ui-1.10.3.full.min.css" rel="stylesheet"/>
<link href="/static/assets/css/datepicker.css" rel="stylesheet"/>
<link href="/static/assets/css/ui.jqgrid.css" rel="stylesheet"/>
<link href="/static/assets/css/ace.min.css" rel="stylesheet"/>
<link href="/static/assets/css/ace-rtl.min.css" rel="stylesheet"/>
<link href="/static/assets/css/ace-skins.min.css" rel="stylesheet"/>
    <style type="text/css">
        #date,#name,#phone{
            width: 100px;
            height: 22px;
        }
        .search{
            margin-left: 800px;
        }
        .export{
            float: left;
        }
        #excel,#allexcel,#search-btn{
            background: rgb(244,244,244);
            border: #cecece solid 1px;

        }
    </style>
{% endblock %}
{% block content %}

        <div class="row">
            <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="x_panel">
                    <div class="x_title">
                        <h2>湖南省脑出血患者草稿箱记录</h2>
                        <div class="clearfix"></div>
                    </div>
                    
                   <div class="export">
 {#                      <input type="BUTTON" id="dedata" value="删除所选记录" />#} 
                        <input type="BUTTON" id="excel" value="导出所选记录" />
                        <input type="BUTTON" id="allexcel" value="导出全部记录" />
                   </div>

                    <div class="search">
                        <span id="name1">填表人姓名</span>
                        <input type="text" value="" id="name">
                        <span id="date1">填表人填表日期</span>
                        <input type="text" value="" id="date">
                        <input type="button" value="搜索" id="search-btn">
                    </div>

                    <table id="grid-table"></table>
                    <div id="grid-pager"></div>

                </div>
            </div>
        </div>
{% endblock %}
{% block js %}
<script src="/static/assets/js/ace-extra.min.js"></script>
<script src="/static/assets/js/jqGrid/jquery.jqGrid.min.js"></script>
<script src="/static/assets/js/jqGrid/i18n/grid.locale-en.js"></script>
<script src="/static/assets/js/ace-elements.min.js"></script>
<script src="/static/assets/js/ace.min.js"></script>
<script src="/static/assets/js/xlsx.full.min.js"></script>

<script type="text/javascript">
            var excelTitle="{{ excelTitle }}"
            excelTitle = excelTitle.replace(/\&quot;/g, '\"');
            excelTitle=JSON.parse(excelTitle);


			jQuery(function($) {
				var grid_selector = "#grid-table";
				var pager_selector = "#grid-pager"

				jQuery(grid_selector).jqGrid({
                    datatype: "json",
                    url:"/wenjuancgx/wenjuancgx_solve/hunan/no1/",
                    mtype: 'POST',
                    height: 600,
                    width: 400,
                    colNames:['记录编号','填表人签名', '填表人联系电话','填表人填写日期'],
                    colModel:[{name: "_id", id: "_id", width: 100},
                              {name: "填表人签名", id: "填表人签名", width: 100},
                              {name: "填表人联系电话", id: "填表人联系电话", width: 100},
                              {name: "填表人填写日期", id: "填表人填写日期", width: 100}
                              ],
                    pager: pager_selector, //分页工具栏
                    altRows: true,
                    rowNum:50, //每页显示记录数
                    viewrecords: true, //是否显示行数
                    rowList:[50,100,200,1000,2000], //可调整每页显示的记录数
                    multiselect: true, //是否支持多选
                    loadComplete : function() {
						var table = this;
						setTimeout(function(){
							updatePagerIcons(table);
							enableTooltips(table);
						}, 0);
					},
                    caption: "湖南省脑出血患者草稿箱记录",
                    autowidth: true
				});

				//switch element when editing inline
				function aceSwitch( cellvalue, options, cell ) {
					setTimeout(function(){
						$(cell) .find('input[type=checkbox]')
								.wrap('<label class="inline" />')
							.addClass('ace ace-switch ace-switch-5')
							.after('<span class="lbl"></span>');
					}, 0);
				}

				//navButtons
				jQuery(grid_selector).jqGrid('navGrid',pager_selector,
					{ 	//navbar options
						edit: false,
						{#editicon : 'icon-pencil blue',#}

						add: false,
						{#addicon : 'icon-plus-sign purple',#}

						del: false,
						delicon : 'icon-trash red',

						search:false,
						searchicon : 'icon-search orange',

						refresh: true,
						refreshicon : 'icon-refresh green',

						view: false,
						viewicon : 'icon-zoom-in grey',
					}
				);

            $("#dedata").click(function() {
                    var gr = jQuery(grid_selector).jqGrid('getGridParam', 'selarrrow'); //获取选中的行集合
                    var selectD=''; //用户选择的需要删除的数据
                     if(gr.length!=0){
                        for (var i = 0;i < gr.length; i++) { //获取选择行的数据标识
                            var ret=$(grid_selector).jqGrid("getRowData", gr[i]);
                            selectD=selectD+ret['_id']+",";
                        }
                       for (var i = 0, l = gr.length; i < l; i++) { //保证同时可以删除多行
                            $(grid_selector).jqGrid("delRowData", gr[0]);
                       }
                       $.ajax({
                            url:"{% url 'DelWenjuan1_cgx' %}",
                            type:"POST",
                            data:{
                                 selectRaw:selectD,
                                 csrfmiddlewaretoken: '{{ csrf_token }}'
                            },
                            success:function(data){
                               ;
                            }
                        })
                    }
                    else{
                        alert("请选择需要删除的行!");
                    }
            });

            $("#excel").click(function() {
                var gr = jQuery(grid_selector).jqGrid('getGridParam','selarrrow');

                var selectD=''; //用户选择的需要导出的数据
                if(gr.length!=0){
                    for (var i = 0;i < gr.length; i++) { //保证同时可以删除多行
                        var ret=$(grid_selector).jqGrid("getRowData", gr[i]);
                        selectD=selectD+ret['_id']+",";
                    }
                    console.log(selectD);
                    $.ajax({
                        url:"/wenjuancgx/ExportWenjuancgx/{{ request.user }}/no1/",
                        type:"POST",
                        data:{
                             selectRaw:selectD,
                             csrfmiddlewaretoken: '{{ csrf_token }}'
                        },
                        success:function(data){
                            var aoa=[];
                            aoa.push(excelTitle);
                            for(var i=0;i<JSON.parse(data).length;i++){
                                aoa.push(JSON.parse(data)[i])
                            }

                            exportSpecialExcel(aoa);
                        }
                    })
                }
                else{
                    alert("请选择需要导出的行!");
                }
            });

            $('#search-btn').click(function () {
                var name = document.querySelector('#name').value
                var date = document.querySelector('#date').value
                jQuery(grid_selector).jqGrid('setGridParam', {postData:{"填表人签名":name,"填表人填写日期":date} }).trigger('reloadGrid');
            })
             $('#allexcel').click(function () {

                let rowNum = jQuery(grid_selector).jqGrid('getGridParam', 'rowNum')//每页的行数
                let total = jQuery(grid_selector).jqGrid('getGridParam', 'records')
                jQuery(grid_selector).jqGrid('setGridParam', {rowNum: total}).trigger('reloadGrid');

                setTimeout(function () {
                    var gr = jQuery(grid_selector).jqGrid("getDataIDs");
                    jQuery(grid_selector).jqGrid('setGridParam', { rowNum: rowNum}).trigger('reloadGrid');
                    var selectD = ''
                    for (var i = 0;i < gr.length; i++) { //保证同时可以删除多行
                         var ret=$(grid_selector).jqGrid("getRowData", gr[i]);
                         selectD=selectD+ret['_id']+",";
                    }
                    $.ajax({
                    url:"/wenjuancgx/ExportWenjuancgx/{{ request.user }}/no1/",
                    type:"POST",
                    data:{
                         selectRaw:selectD,
                         csrfmiddlewaretoken: '{{ csrf_token }}'
                    },
                    success:function(data){
                        var aoa=[];
                        aoa.push(excelTitle);
                        for(var i=0;i<JSON.parse(data).length;i++){
                            aoa.push(JSON.parse(data)[i])
                        }
                        exportSpecialExcel(aoa);
                    }
                })
                },100)
            });
				//replace icons with FontAwesome icons like above
				function updatePagerIcons(table) {
					var replacement =
					{
						'ui-icon-seek-first' : 'icon-double-angle-left bigger-140',
						'ui-icon-seek-prev' : 'icon-angle-left bigger-140',
						'ui-icon-seek-next' : 'icon-angle-right bigger-140',
						'ui-icon-seek-end' : 'icon-double-angle-right bigger-140'
					};
					$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
						var icon = $(this);
						var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
						if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
					})
				}

				function enableTooltips(table) {
					$('.navtable .ui-pg-button').tooltip({container:'body'});
					$(table).find('.ui-pg-div').tooltip({container:'body'});
				}

			});

			//下面代码为实现Excel导出功能
            //将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
            function sheet2blob(sheet, sheetName) {
                sheetName = sheetName || 'sheet1';
                var workbook = {
                    SheetNames: [sheetName],
                    Sheets: {}
                };
                workbook.Sheets[sheetName] = sheet;
                // 生成excel的配置项
                var wopts = {
                    bookType: 'xlsx', // 要生成的文件类型
                    bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                    type: 'binary'
                };
                var wbout = XLSX.write(workbook, wopts);
                var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});
                // 字符串转ArrayBuffer
                function s2ab(s) {
                    var buf = new ArrayBuffer(s.length);
                    var view = new Uint8Array(buf);
                    for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                    return buf;
                }
                return blob;
            }

            /*
             * 通用的打开下载对话框方法，没有测试过具体兼容性
             * @param url 下载地址，也可以是一个blob对象，必选
             * @param saveName 保存文件名，可选
             */
             function openDownloadDialog(url, saveName)
            {
                if(typeof url == 'object' && url instanceof Blob)
                {
                    url = URL.createObjectURL(url); // 创建blob地址
                }
                var aLink = document.createElement('a');
                aLink.href = url;
                aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
                var event;
                if(window.MouseEvent) event = new MouseEvent('click');
                else
                {
                    event = document.createEvent('MouseEvents');
                    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                }
                aLink.dispatchEvent(event);
            }

            function exportSpecialExcel(aoa) {
                var sheet = XLSX.utils.aoa_to_sheet(aoa);
                openDownloadDialog(sheet2blob(sheet), '湖南省脑出血患者草稿箱记录.xlsx');
            }
		</script>

{% endblock %}
